//
//  MainTabar.m
//  SinaWeibo
//
//  Created by Apple on 16/8/6.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "MainTabar.h"

@interface MainTabar()

@property (weak, nonatomic) UIButton *plusButton;

@end


@implementation MainTabar

-(instancetype)initWithFrame:(CGRect)frame{
    
    if (self == [super initWithFrame:frame]) {
        [self setPlusButton];
    }
    return self;
    
}

//初始化button，还未设置frame。所以不会显示,要在layoutsubviews中设置他的frame.
-(void)setPlusButton{
    
    UIButton *plusButton = [[UIButton alloc]init];
    
    //设置背景图
    [plusButton setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button"] forState:UIControlStateNormal];
    
    //设置图片
    [plusButton setImage:[UIImage imageNamed:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
    
    //设置背景图--点击时
    [plusButton setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
    
    //设置图片－－点击时
    [plusButton setImage:[UIImage imageNamed:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];

    //关联plusButton，在layoutsubview设置frame
    self.plusButton = plusButton;
    
    //添加到tabbr中
    [self addSubview:plusButton];
    
    //监听plusBtn事件
    [plusButton addTarget:self action:@selector(clickPlusBtn:) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)clickPlusBtn:(UIButton *)plusBtn{
    //执行代理
    if ([self.delegate respondsToSelector:@selector(mainTabbar:plusBtn:)]) {
        [self.delegate performSelector:@selector(mainTabbar:plusBtn:) withObject:self withObject:plusBtn];
    }
    
}


//设置tabBar中间的按钮为空。
-(void)layoutSubviews{
    
    [super layoutSubviews];
    
    NSInteger index = 0;
    for (UIView *childView in self.subviews) {
        
        //遍历时候要把且不是uibutton类型加进去，否则添加plusButton后会被遍历并且设置frame.
        if ([childView isKindOfClass:[UIControl class]] && ![childView isKindOfClass:[UIButton class]]) {
            CGFloat childViewWidth = self.frame.size.width/5;
            CGFloat childViewHeight = self.frame.size.height;
            CGFloat childViewX = index * childViewWidth;
            CGFloat childViewY = 0;
            
            if (index == 1) {
                index++;
            }
            index++;
            childView.frame = CGRectMake(childViewX, childViewY, childViewWidth, childViewHeight);
            
        }
    }
    
    //设置plusButton的frame.
    self.plusButton.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    [self.plusButton sizeToFit];
    

    
}



@end
